import axios from 'axios'

// 配置基础URL
const API_BASE_URL = 'http://localhost:8081'

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 用户管理API
export const userAPI = {
  // 用户注册
  register: (userData) => api.post('/api/users/register', userData),
  
  // 用户登录
  login: (loginData) => api.post('/api/users/login', loginData),
  
  // 获取用户信息
  getUserInfo: (userId) => api.get(`/api/users/${userId}`),
  
  // 更新用户信息
  updateUser: (userId, userData) => api.put(`/api/users/${userId}`, userData),
  
  // 检查用户密码
  checkPassword: (userId, password) => api.get(`/api/users/checkPassword/user/${userId}`, {
    params: { password }
  }),
  
  // 删除用户
  deleteUser: (userId) => api.delete(`/api/users/${userId}`),
  
  // 获取所有用户
  getAllUsers: () => api.get('/api/users'),
  
  // 检查用户是否存在
  userExists: (userId) => api.get(`/api/users/${userId}/exists`),
  
  // 检查账号是否存在
  accountExists: (userAccount) => api.get(`/api/users/account/${userAccount}/exists`)
}

export default api
